<?php

namespace App\Http\Controllers\BuyProcess;

use App\Http\Controllers\Component\MasterResponseController;
use App\Http\Requests\BuyProcess\OrderRequest;
use App\Jobs\OrderTimeOutJob;
use App\Model\Address;
use App\Model\ChinaProvince;
use App\Model\Goods;
use App\Model\Order;
use DB;
use Auth;
use Webpatser\Uuid\Uuid;

class CreateOrderController extends MasterResponseController
{
    public function __construct()
    {
        $this->middleware('unlogin');
    }

    public function index($id)
    {
        $craft = DB::table('goods_v')->where('id', $id)->first();
        $address = Address::where('user_id', Auth::user()->id)->get();
        $provinces = ChinaProvince::all();
        $data = array(
            'craft' => $craft,
            'address' => $address,
            'provinces' => $provinces
        );
        return view('buy_process.createOrder', compact('data'));
    }

    public function createOrder(OrderRequest $request, Order $order)
    {
        $hasOrder = Order::where('goods_id', $request['goods_id'])
            ->where('user_id', Auth::user()->id)->count('*');

        $goodsStatus=Goods::where('id',$request['goods_id'])->value('status');

        if ($hasOrder > 0) {
            return parent::error('在您的订单中已有此作品');
        } else {
            if ($goodsStatus!=1){
                return parent::error('抱歉，该作品已被其他用户订购');
            }
            $id = Uuid::generate(4);
            $request['id'] = $id;
            $request['user_id'] = Auth::user()->id;
            $request['status'] = 0;
            $order->create($request->all());

            //定时任务 15分后执行
            OrderTimeOutJob::dispatch($id->string)
                ->onConnection('redis')
                ->onQueue('orderTimeOut');
            $data = array(
                'orderId' => $id->string
            );
            return parent::withData($data);
        }
    }
}
